package com.hebi.xzspring.initailizer;

import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@HandlesTypes(WebApplicationInitializer.class)
public class XzSpringServletContainerInitalizer implements ServletContainerInitializer {

	@Override
	public void onStartup(Set<Class<?>> initalizers, ServletContext servletContext) throws ServletException {

		List<WebApplicationInitializer> subInits = new LinkedList<>();

		for (Class<?> initialClazz :initalizers) {
			try {
				if (!initialClazz.isInterface() && !Modifier.isAbstract(initialClazz.getModifiers())
						&& WebApplicationInitializer.class.isAssignableFrom(initialClazz)) {
					subInits.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(initialClazz).newInstance());
				}
			} catch (Throwable ex) {
				ex.printStackTrace();
			}
		}

		servletContext.log(subInits.size() + " Spring WebApplicationInitializers detected on classpath");
		if (!subInits.isEmpty()) {
			for (WebApplicationInitializer subInit : subInits) {
				subInit.onStartup(servletContext);
			}
		}
	}
}
